package com.sujeet.learning.xmlrpc;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.xmlrpc.XmlRpcException;
import org.apache.xmlrpc.client.XmlRpcClient;
import org.apache.xmlrpc.client.XmlRpcClientConfigImpl;
import org.apache.xmlrpc.client.XmlRpcCommonsTransportFactory;

public class SchedulerClient {
	public static void addEvents(XmlRpcClient client) throws XmlRpcException,
			IOException {
		System.out.println("\nAdding events...\n");
		// Parameters for events
		List<Object> params = new ArrayList<Object>();
		// Add an event for next month
		params.add("Proofread final draft");
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, 1);
		params.add(cal.getTime());
		// Add the event
		if (((Boolean) client.execute("Scheduler.addEvent", params))
				.booleanValue()) {
			System.out.println("Event added.");
		} else {
			System.out.println("Could not add event.");
		}
		// Add an event for tomorrow
		params.clear();
		params.add("Submit final draft");
		cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_MONTH, 1);
		params.add(cal.getTime());
		// Add the event
		if (((Boolean) client.execute("Scheduler.addEvent", params))
				.booleanValue()) {
			System.out.println("Event added.");
		} else {
			System.out.println("Could not add event.");
		}

	}

	public static void listEvents(XmlRpcClient client) throws XmlRpcException,
			IOException {
		System.out.println("\nListing events...\n");

		// Get the events in the scheduler
		List<Object> params = new ArrayList<Object>();
		Object[] events = (Object[]) client.execute(
				"Scheduler.getListOfEvents", params);
		for (int i = 0; i < events.length; i++) {
			System.out.println((String) events[i]);
		}
	}

	public static void main(String args[]) {

		XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();
		try {
			config.setServerURL(new URL("http://127.0.0.1:8083/"));
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		XmlRpcClient client = new XmlRpcClient();
		client.setTransportFactory(new XmlRpcCommonsTransportFactory(client));
		client.setConfig(config);
		try {
			addEvents(client);
			listEvents(client);
		} catch (XmlRpcException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}
